# config_manager.py
import configparser
import os


class ConfigManager:
    def __init__(self, config_file='config.ini'):
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self.load_config()
        # 确保Control配置部分存在
        if 'Control' not in self.config:
            self.config['Control'] = {}
        if 'window_on_top' not in self.config['Control']:
            self.config['Control']['window_on_top'] = 'False'
        if 'window_width' not in self.config['Control']:
            self.config['Control']['window_width'] = '1200'
        if 'window_height' not in self.config['Control']:
            self.config['Control']['window_height'] = '800'
        if 'auto_submit' not in self.config['Control']:
            self.config['Control']['auto_submit'] = 'True'
        if 'log_enabled' not in self.config['Control']:
            self.config['Control']['log_enabled'] = 'True' # 默认启用日志
        if 'bastion_columns' not in self.config['Control']:
            self.config['Control']['bastion_columns'] = "路段名称,堡垒机IP,用户名,登录密码,堡垒机品牌,备注"
        self.save_config()

    def load_config(self):
        """加载配置文件，如果不存在则创建默认配置"""
        if os.path.exists(self.config_file):
            self.config.read(self.config_file, encoding='utf-8')

        # 确保基本配置部分存在
        if 'Chrome' not in self.config:
            self.config['Chrome'] = {}

        # 设置默认值（如果不存在）
        chrome_section = self.config['Chrome']
        if 'chrome_path' not in chrome_section:
            chrome_section['chrome_path'] = ''
        if 'driver_path' not in chrome_section:
            chrome_section['driver_path'] = ''

        # 确保基本配置部分存在
        if 'Login' not in self.config:
            self.config['Login'] = {}
        # 设置默认值（如果不存在）
        login_section = self.config['Login']
        if 'login_path' not in login_section:
            login_section['login_path'] = ''

    def save_config(self):
        """保存配置到文件"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            self.config.write(f)

    def get_chrome_path(self):
        """获取Chrome可执行文件路径"""
        return self.config['Chrome']['chrome_path']

    def get_driver_path(self):
        """获取Chrome驱动文件路径"""
        return self.config['Chrome']['driver_path']

    def get_login_path(self):
        """获取Chrome驱动文件路径"""
        # print(self.config['Login']['login_path'])
        return self.config['Login']['login_path']

    def get_servers_path(self):
        """获取Chrome驱动文件路径"""
        # print(self.config['Login']['login_path'])
        if 'Servers' not in self.config:
            self.config['Servers'] = {}
        if 'servers_path' not in self.config['Servers']:
            self.config['Servers']['servers_path'] = 'login.xlsx'
            self.save_config()
        return self.config['Servers']['servers_path']


    def set_chrome_path(self, path):
        """设置Chrome可执行文件路径"""
        self.config['Chrome']['chrome_path'] = path
        self.save_config()

    def set_driver_path(self, path):
        """设置Chrome驱动文件路径"""
        self.config['Chrome']['driver_path'] = path
        self.save_config()

    def set_login_path(self, path):
        """设置Chrome驱动文件路径"""
        self.config['Login']['login_path'] = path
        self.save_config()

    def set_servers_path(self, path):
        """设置Chrome驱动文件路径"""
        self.config['Servers']['login_path'] = path
        self.save_config()

    def get_window_on_top(self):
        """获取窗口置顶设置"""
        return self.config['Control'].getboolean('window_on_top')
        self.save_config()

    def get_window_size(self):
        """获取窗口大小配置"""
        try:
            width = int(self.config['Control']['window_width'])
            height = int(self.config['Control']['window_height'])
            return (width, height)
        except:
            return (1200, 800)

    def set_window_size(self, width, height):
        """设置窗口大小配置"""
        self.config['Control']['window_width'] = str(width)
        self.config['Control']['window_height'] = str(height)
        self.save_config()

    def set_window_on_top(self, on_top):
        """设置窗口置顶"""
        self.config['Control']['window_on_top'] = str(on_top)
        self.save_config()

    def get_auto_submit(self):
        """获取自动提交设置"""
        return self.config['Control'].getboolean('auto_submit')

    def set_auto_submit(self, auto_submit):
        """设置自动提交"""
        self.config['Control']['auto_submit'] = str(auto_submit)
        self.save_config()

    def get_bastion_file_path(self):
        """获取堡垒机文件路径"""
        return self.get_login_path()

    def get_log_enabled(self):
        """获取日志启用状态"""
        return self.config['Control'].getboolean('log_enabled', fallback=True)

    def set_log_enabled(self, enabled):
        """设置日志启用状态"""
        self.config['Control']['log_enabled'] = str(enabled)
        self.save_config()

    def get_bastion_columns(self) -> list:
        """获取堡垒机表格列名列表"""
        columns_str = self.config['Control'].get('bastion_columns', "路段名称,堡垒机IP,用户名,登录密码,堡垒机品牌,备注")
        return [col.strip() for col in columns_str.split(',')]

    def set_bastion_columns(self, columns: list):
        """设置堡垒机表格列名列表"""
        self.config['Control']['bastion_columns'] = ",".join(columns)
        self.save_config()